package com.itheima.filter;



import com.itheima.pojo.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter(filterName = "loginFilter", urlPatterns = "/*")  // /*表示全部拦截
public class AuthFilter implements Filter, Ordered {

    @Value("${sign}")
    private String sign;

    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String USER = "user";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入拦截器");
        //获取请求响应对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        System.out.println(request.getRequestURI());
        //if (request.getRequestURI().contains("/login/login") || request.getRequestURI().contains("/login/register")||request.getRequestURI().contains("/index/**")||request.getRequestURI().contains("/sysDictData/getListByDictTypeList")) {
            filterChain.doFilter(request, response);
            return;
       // }
        //2. 不是登录请求, 且请求中没有携带token , 则拒绝访问
        //2.1 获取请求中的cookie
//        String token = this.getJtiFromCookies(request);
//        //2.2 判断是否携带cookie
//        if (StringUtils.isEmpty(token)) {
//           //异常解析器,可以将异常传入全局异常处理器中
//            resolver.resolveException(request,response,null,new RuntimeException("token无效或过期!"));
//            return;
//        }
//        try {
//            //校验token
//            Claims claims = Jwts.parser().setSigningKey(sign).parseClaimsJws(token).getBody();
//            System.out.println("claims:"+claims);
//            String username = claims.get("username", String.class);
//            User user = (User) redisTemplate.boundHashOps(USER).get(username);
//            if (user==null){
//                resolver.resolveException(request,response,null,new RuntimeException("用户被管理员强制退出"));
//                return;
//            }
//            //放行
//            filterChain.doFilter(request,response);
//            return;
//        } catch (Exception e) {
//            e.printStackTrace();
//            //异常解析器,可以将异常传入全局异常处理器中
//            resolver.resolveException(request,response,null,new RuntimeException("token无效或过期!"));
//            return;
//        }
    }

    /**
     * 从cookie中获取token
     *
     * @param request
     * @return
     */
    private String getJtiFromCookies(HttpServletRequest request) {
        //1.获取cookie对象
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())){
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    @Override
    public int getOrder() {
        return 0;
    }


}
